import { Injectable } from '@angular/core';
import { APIBase, ListOption } from 'app/modules/base/api-base';
import { HttpClient } from '@angular/common/http';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class WebMessageService extends APIBase<FormData, WebMessageTo> implements Resolve<any> {
  constructor(private http: HttpClient) {
    super(http, '/api/admin/message');
  }
  sent = new (class extends APIBase<any, WebMessage> {
    async list(opt: WebMessageListOption) {
      const result = await super.list(opt);
      result.list.forEach(msg => {
        msg.message = msg;
      });
      return result;
    }
    async get(id: number) {
      const result = await super.get(id);
      result.message = result;
      return result;
    }
  })(this.http, '/api/admin/message_sent');

  brothers(mid: number) {
    return this.http
      .get<{ prev: number; next: number }>(`${this.baseURL}/${mid}/brother`)
      .toPromise();
  }

  resolve(route: ActivatedRouteSnapshot) {
    const opt: WebMessageListOption = {};
    opt.page = Number(route.queryParamMap.get('page')) || 1;
    opt.count = Number(route.queryParamMap.get('count')) || 10;
    const keyword = route.queryParamMap.get('keyword');
    if (keyword) {
      opt.keyword = keyword;
    }

    const status = route.paramMap.get('status') as WebMessageStatus;
    if (status === WebMessageStatus.Sent) {
      return this.sent.list(opt);
    }
    if (status != WebMessageStatus.All) {
      opt.status = status;
    }
    return this.list(opt);
  }
}

export interface WebMessageListOption extends ListOption {
  status?: WebMessageStatus;
  keyword?: string;
}

export enum WebMessageStatus {
  All = 'all',
  Read = 'read',
  Unread = 'unread',
  Sent = 'sent',
}

export interface WebMessageTo {
  id: number;
  created_at: string;
  updated_at: string;
  status: WebMessageStatus;
  message: WebMessage;
  receiver: Admin;
}

export interface WebMessage {
  id: number;
  created_at: string;
  updated_at: string;
  to?: WebMessageTo;
  sender?: Admin;
  title: string;
  content: string;
  text: string;

  // 指向自己，为方便在表格中保持一直访问
  message?: WebMessage;
}

interface Admin {
  id: number;
  username: string;
}
